package com.example.app10_listview_demo.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.app10_listview_demo.R;

import java.util.List;

public class AppAdapter extends BaseAdapter {

    private final Context context;

    private final List<AppInfo> data;

    public AppAdapter(Context context, List<AppInfo> data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.isEmpty() ? 0 : data.size();
    }

    @Override
    public Object getItem(int position) {
        return data.isEmpty() ? new AppInfo() : data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    /**
     * 获取带数据的当前行的视图对象
     * @param position 位置下标
     * @param convertView 视图对象
     * @param parent 视图对象的父容器
     * @return 带数据的当前行的视图对象
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 创建一个当前行的ViewHolder对象
        ViewHolder viewHolder = null;
        // 如果convertView == null, 加载布局文件对象
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = View.inflate(context, R.layout.item_main, null);
            viewHolder.ivItemMainIcon = convertView.findViewById(R.id.iv_item_main_icon);
            viewHolder.tvItemMainName = convertView.findViewById(R.id.tv_item_main_name);
            // 将Holder对象保存到convertView上
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // 获取数据
        AppInfo appInfo = data.get(position);

        viewHolder.ivItemMainIcon.setImageDrawable(appInfo.getIcon());
        viewHolder.tvItemMainName.setText(appInfo.getAppName());

        return convertView;
    }

    // 使用ViewHolder优化ListView
    class ViewHolder {
        ImageView ivItemMainIcon;
        TextView tvItemMainName;
    }
}
